/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support.wx.util;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.SortedMap;

import com.yanlight.util.HMACSHA256;
import com.yanlight.util.LogUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;

import com.yanlight.Constants;
import com.yanlight.util.EncryptUtil;
import com.yanlight.util.MapUtil;
import sun.security.provider.MD5;

import static com.sun.org.apache.xml.internal.serialize.OutputFormat.Defaults.Encoding;

/**
 * @author haolw
 * @time 2017/07/20
 */
public class SignatureUtil {

    /**
     * js-sdk config接口注入权限验证 签名
     *
     * @param map
     * @return
     */
    public static String createJsConfigSignature(SortedMap<String, String> map) {
        String signStr = MapUtil.toUrlParams(map);
        String sign = DigestUtils.sha1Hex(signStr.getBytes(Constants.DEFAULT_CHARSET));
        return sign;
    }

    /**
     * API签名 ,mchKey:微信支付API密钥
     *
     * @param params
     * @param mchKey
     * @return
     */
    public static String createApiSign(SortedMap<String, String> params, String mchKey) {
        String sign = getString(params, mchKey);
        LogUtil.showLog(sign);
        return EncryptUtil.md5(sign).toUpperCase();
    }

    /**
     * API签名 ,mchKey:微信支付API密钥
     *
     * @param params
     * @param mchKey
     * @return
     */
    public static String createApiSignHMAC(SortedMap<String, String> params, String mchKey) {
        String sign = getString(params, mchKey);
        LogUtil.showLog(sign);
        return HMACSHA256.sha256_HMAC(sign, mchKey).toUpperCase();
    }

    private static String getString(SortedMap<String, String> params, String mchKey) {
        StringBuilder signBuilder = new StringBuilder(16);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!"sign".equals(key) && !"key".equals(key) && StringUtils.isNotBlank(value)) {
                signBuilder.append(key).append("=").append(value).append("&");
            }
        }
        return signBuilder.append("key=").append(mchKey).toString();
    }
}
